<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>轮胎管理系统 - 轮胎列表</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
  <!-- 引入 jQuery 和 jQuery UI 用于自动补全 -->
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/smoothness/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
  <!-- 引入 Font Awesome 图标 -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <style>
    .status-badge {
      font-size: 0.8rem;
    }
    .table th {
      background-color: #f8f9fa;
    }
    .action-buttons .btn {
      margin-right: 5px;
      margin-bottom: 5px;
    }
    .axle-badge {
      background-color: #6c757d;
    }
    .btn-visualization {
      background-color: #9c27b0;
      border-color: #9c27b0;
      color: white;
    }
    .btn-visualization:hover {
      background-color: #7b1fa2;
      border-color: #7b1fa2;
    }
    .btn-statistics {
      background-color: #28a745;
      border-color: #28a745;
      color: white;
    }
    .btn-statistics:hover {
      background-color: #218838;
      border-color: #1e7e34;
    }

    .btn-settlement {
      background-color: #007bff;
      border-color: #007bff;
      color: white;
    }
    .btn-settlement:hover {
      background-color: #0056b3;
      border-color: #004085;
    }

    .btn-cost {
      background-color: #ff9800;
      border-color: #ff9800;
      color: white;
    }
    .btn-cost:hover {
      background-color: #f57c00;
      border-color: #f57c00;
    }
    .ui-autocomplete {
      max-height: 200px;
      overflow-y: auto;
      overflow-x: hidden;
      z-index: 1000;
    }
    .ui-autocomplete-loading {
      background: white url('https://code.jquery.com/ui/1.13.0/themes/smoothness/images/ui-anim_basic_16x16.gif') right center no-repeat;
      background-size: 16px 16px;
    }
    .loading-overlay {
      display: none;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(255, 255, 255, 0.8);
      z-index: 1000;
      justify-content: center;
      align-items: center;
    }
    .cost-summary-card {
      transition: all 0.3s ease;
    }
    .cost-summary-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .chart-container {
      height: 300px;
      margin-bottom: 20px;
    }
    .table-costs th {
      background-color: #e9ecef;
    }
    .cost-positive {
      color: #dc3545;
      font-weight: bold;
    }
    .cost-negative {
      color: #28a745;
      font-weight: bold;
    }
    /* 分页样式优化 */
    .pagination-container {
      border-top: 1px solid #e9ecef;
      background-color: #f8f9fa;
    }
    .page-info {
      font-weight: 500;
      color: #495057;
    }
    .page-item.active .page-link {
      background-color: #007bff;
      border-color: #007bff;
    }
    .page-link {
      color: #007bff;
      border: 1px solid #dee2e6;
      padding: 0.375rem 0.75rem;
    }
    .page-link:hover {
      color: #0056b3;
      background-color: #e9ecef;
      border-color: #dee2e6;
    }
    .readonly-field {
      background-color: #e9ecef;
      cursor: not-allowed;
      opacity: 0.8;
    }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container">
    <a class="navbar-brand" href="/api/tires">轮胎管理系统</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav me-auto">
        <li class="nav-item">
          <a class="nav-link active" href="/api/tires">轮胎列表</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/batch-add">批量添加轮胎</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/usage">查询使用记录</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/visualization/">轮胎可视化</a>
        </li>
        <!-- 新增统计页面导航项 -->
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/statistics">轮胎统计</a>
        </li>
        <!-- 新增费用结算导航项 -->
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/settlement">费用结算</a>
        </li>
        <!-- 新增费用统计导航项 -->
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/cost-statistics">费用统计报表</a>
        </li>
        <!-- 新增用户管理导航项 - 仅管理员可见 -->
        <li class="nav-item" id="userManagementNavItem" style="display: none;">
          <a class="nav-link" href="/user-management">用户管理</a>
        </li>
      </ul>
      <div class="navbar-nav">
        <span class="navbar-text me-3" id="current-user">
          <i class="fas fa-user me-1"></i>
          用户
        </span>
        <button class="btn btn-outline-light btn-sm" onclick="logout()">
          <i class="fas fa-sign-out-alt me-1"></i>退出登录
        </button>
      </div>
    </div>
  </div>
</nav>

<div class="container mt-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h1>轮胎列表</h1>
    <div>
      <a href="/api/tires/batch-add" class="btn btn-primary">批量添加轮胎</a>
      <a href="/api/tires/usage" class="btn btn-info">查询使用记录</a>
      <a href="/api/tires/visualization/" class="btn btn-visualization">轮胎可视化</a>
      <!-- 新增统计按钮 -->
      <a href="/api/tires/statistics" class="btn btn-statistics">轮胎统计报表</a>
      <!-- 新增费用结算按钮 -->
      <a href="/api/tires/settlement" class="btn btn-settlement">费用结算</a>
      <!-- 新增费用统计按钮 -->
      <a href="/api/tires/cost-statistics" class="btn btn-cost">费用统计报表</a>
      <!-- 新增用户管理按钮 - 仅管理员可见 -->
      <a href="/user-management" class="btn btn-warning" id="userManagementBtn" style="display: none;">
        <i class="fas fa-users me-1"></i>用户管理
      </a>
    </div>
  </div>

  <!-- 统计信息卡片 -->
  <div class="row mb-4">
    <div class="col-md-3">
      <div class="card text-white bg-primary">
        <div class="card-body">
          <h5 class="card-title">总轮胎数</h5>
          <p class="card-text display-6" id="totalTiresCount">0</p>
        </div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card text-white bg-success">
        <div class="card-body">
          <h5 class="card-title">使用中</h5>
          <p class="card-text display-6" id="activeTiresCount">0</p>
        </div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card text-white bg-secondary">
        <div class="card-body">
          <h5 class="card-title">已报废</h5>
          <p class="card-text display-6" id="scrappedTiresCount">0</p>
        </div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card text-white bg-warning">
        <div class="card-body">
          <h5 class="card-title">有修补记录</h5>
          <p class="card-text display-6" id="repairedTiresCount">0</p>
        </div>
      </div>
    </div>
  </div>

  <!-- 搜索和筛选区域 -->
  <div class="card mb-4">
    <div class="card-header">
      <h5 class="mb-0">搜索和筛选</h5>
    </div>
    <div class="card-body">
      <form id="searchForm" class="row g-3">
        <div class="col-md-3">
          <label for="searchTireNumber" class="form-label">轮胎号</label>
          <input type="text" class="form-control" id="searchTireNumber" name="tireNumber"
                 placeholder="输入轮胎号，支持自动补全">
        </div>

        <!-- 车牌号输入框 - 根据用户角色动态设置 -->
        <div class="col-md-3">
          <label for="searchPlateNumber" class="form-label">车牌号</label>
          <input type="text" class="form-control" id="searchPlateNumber" name="plateNumber"
                 placeholder="输入车牌号，支持自动补全">
        </div>

        <!-- 运输公司选择框 - 根据用户角色动态设置 -->
        <div class="col-md-2">
          <label for="searchCompany" class="form-label">运输公司</label>
          <select class="form-select" id="searchCompany" name="company">
            <option value="">全部</option>
            <!-- 使用 Thymeleaf 动态生成运输公司选项 -->
            <option th:each="company : ${transportCompanies}"
                    th:value="${company}"
                    th:text="${company}"></option>
          </select>
        </div>

        <div class="col-md-2">
          <label for="searchStatus" class="form-label">状态</label>
          <select class="form-select" id="searchStatus" name="status">
            <option value="">全部</option>
            <option value="active">使用中</option>
            <option value="scrapped">已报废</option>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label">&nbsp;</label>
          <div>
            <button type="submit" class="btn btn-primary">搜索</button>
            <button type="button" id="resetBtn" class="btn btn-secondary">重置</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- 轮胎列表表格 -->
  <div class="card position-relative">
    <div class="loading-overlay" id="loadingOverlay">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
    </div>
    <div class="card-header d-flex justify-content-between align-items-center">
      <h5 class="mb-0">轮胎列表</h5>
      <div class="text-muted small" id="tiresPageInfo">
        显示 0-0 条，共 0 条
      </div>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-striped table-hover mb-0">
          <thead>
          <tr>
            <th>轮胎号</th>
            <th>车牌号</th>
            <th>轴号/位置</th>
            <th>运输公司</th>
            <th>品牌</th>
            <th>型号</th>
            <th>装胎日期</th>
            <th>装胎公里数</th>
            <th>当前公里数</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody id="tiresTableBody">
          <!-- 数据将通过JavaScript动态填充 -->
          </tbody>
        </table>
      </div>
    </div>
    <!-- 分页容器 - 放在卡片内部 -->
    <div class="card-footer pagination-container">
      <nav aria-label="轮胎列表分页">
        <ul class="pagination justify-content-center mb-0" id="tiresPagination">
          <!-- 分页将通过JavaScript动态生成 -->
        </ul>
      </nav>
    </div>
  </div>
</div>

<footer class="bg-dark text-white mt-5 py-4">
  <div class="container text-center">
    <p class="mb-0">轮胎管理系统 &copy; 2025</p>
  </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
  // 认证相关函数
  function getAuthToken() {
    return localStorage.getItem('token');
  }

  function getUserInfo() {
    const userInfoStr = localStorage.getItem('userInfo');
    return userInfoStr ? JSON.parse(userInfoStr) : null;
  }

  function checkAuth() {
    const token = getAuthToken();
    const userInfo = getUserInfo();

    if (!token || !userInfo) {
      // 清除可能存在的无效数据
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');

      // 重定向到登录页
      window.location.href = '/login';
      return false;
    }

    return true;
  }

  // 退出登录
  async function logout() {
    try {
      const token = getAuthToken();
      if (token) {
        await fetch('/api/auth/logout', {
          method: 'POST',
          headers: {
            'Authorization': token
          }
        });
      }
    } catch (error) {
      console.error('退出登录失败:', error);
    } finally {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      window.location.href = '/login';
    }
  }

  // 全局路由守卫 - 拦截所有页面跳转
  function setupGlobalNavigationGuard() {
    console.log('设置全局路由守卫...');

    // 拦截所有链接点击
    document.addEventListener('click', function(e) {
      const link = e.target.closest('a');
      if (link && link.href && link.href.startsWith(window.location.origin)) {
        // 检查认证状态
        if (!checkAuth()) {
          console.log('认证失败，阻止导航到: ' + link.href);
          e.preventDefault();
          e.stopPropagation();
          return false;
        } else {
          console.log('认证通过，允许导航到: ' + link.href);
        }
      }
    });

    // 拦截浏览器的前进后退按钮
    window.addEventListener('popstate', function() {
      console.log('检测到浏览器导航事件');
      if (!checkAuth()) {
        // 如果认证失败，重定向到登录页
        console.log('认证失败，重定向到登录页');
        window.location.href = '/login';
      }
    });

    // 重写 history 方法以拦截编程式导航
    const originalPushState = history.pushState;
    const originalReplaceState = history.replaceState;

    history.pushState = function(state, title, url) {
      console.log('检测到 pushState 导航: ' + url);
      if (!checkAuth()) {
        console.log('认证失败，阻止 pushState 导航');
        window.location.href = '/login';
        return;
      }
      return originalPushState.apply(this, arguments);
    };

    history.replaceState = function(state, title, url) {
      console.log('检测到 replaceState 导航: ' + url);
      if (!checkAuth()) {
        console.log('认证失败，阻止 replaceState 导航');
        window.location.href = '/login';
        return;
      }
      return originalReplaceState.apply(this, arguments);
    };

    console.log('全局路由守卫设置完成');
  }

  // 页面加载时初始化
  document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，初始化认证检查...');

    // 检查认证
    if (!checkAuth()) {
      console.log('初始认证检查失败');
      return;
    }

    console.log('初始认证检查通过');

    // 设置全局路由守卫
    setupGlobalNavigationGuard();

    // 显示用户信息
    const userInfo = getUserInfo();
    if (userInfo && document.getElementById('current-user')) {
      const currentUserElement = document.getElementById('current-user');
      currentUserElement.innerHTML = `<i class="fas fa-user me-1"></i>${userInfo.username}`;
      console.log('用户信息显示完成: ' + userInfo.username);

      // 如果是管理员，显示用户管理链接
      if (userInfo.role === 'ADMIN') {
        document.getElementById('userManagementNavItem').style.display = 'block';
        document.getElementById('userManagementBtn').style.display = 'inline-block';
      }
    }

    // 初始化页面功能
    initPage();
  });

  // 页面功能初始化
  function initPage() {
    console.log('初始化页面功能...');

    // 获取用户信息
    const userInfo = getUserInfo();
    const userRole = userInfo ? userInfo.role : '';
    const userTransportCompany = userInfo ? userInfo.transportCompany : '';
    const userVehiclePlateNumber = userInfo ? userInfo.vehiclePlateNumber : '';

    // 轮胎列表分页信息
    let tiresCurrentPage = 1;
    const tiresPageSize = 10;
    let tiresTotalRecords = 0;
    let tiresTotalPages = 1;
    let allTiresData = [];

    // 根据用户角色设置搜索表单
    setupSearchFormForUserRole(userRole, userTransportCompany, userVehiclePlateNumber);

    // 只有管理员角色需要加载运输公司列表，司机和公司角色不需要
    if (userRole === 'ADMIN') {
      loadTransportCompanies();
    }
    // 初始加载数据
    loadTires();

    // 修改 setupSearchFormForUserRole 函数
    function setupSearchFormForUserRole(role, transportCompany, vehiclePlateNumber) {
      const companySelect = document.getElementById('searchCompany');
      const plateNumberInput = document.getElementById('searchPlateNumber');

      if (role === 'DRIVER') {
        // 司机角色：固定运输公司和车牌号
        if (companySelect && transportCompany) {
          // 清空现有选项
          companySelect.innerHTML = '';

          // 添加"全部"选项
          const allOption = document.createElement('option');
          allOption.value = '';
          allOption.textContent = '全部';
          companySelect.appendChild(allOption);

          // 添加司机所属运输公司选项
          const driverCompanyOption = document.createElement('option');
          driverCompanyOption.value = transportCompany;
          driverCompanyOption.textContent = transportCompany;
          companySelect.appendChild(driverCompanyOption);

          // 设置选中值并禁用
          companySelect.value = transportCompany;
          companySelect.disabled = true;
          companySelect.classList.add('readonly-field');
        }

        if (plateNumberInput && vehiclePlateNumber) {
          plateNumberInput.value = vehiclePlateNumber;
          plateNumberInput.disabled = true;
          plateNumberInput.classList.add('readonly-field');
          plateNumberInput.placeholder = '固定车牌号: ' + vehiclePlateNumber;
        }
      } else if (role === 'COMPANY') {
        // 公司角色：固定运输公司
        if (companySelect && transportCompany) {
          // 清空现有选项
          companySelect.innerHTML = '';

          // 添加"全部"选项
          const allOption = document.createElement('option');
          allOption.value = '';
          allOption.textContent = '全部';
          companySelect.appendChild(allOption);

          // 添加公司所属运输公司选项
          const companyOption = document.createElement('option');
          companyOption.value = transportCompany;
          companyOption.textContent = transportCompany;
          companySelect.appendChild(companyOption);

          // 设置选中值并禁用
          companySelect.value = transportCompany;
          companySelect.disabled = true;
          companySelect.classList.add('readonly-field');
        }
        // 车牌号可以自由输入
      }
      // 管理员角色：所有字段都可编辑，不需要特殊处理
    }


    // 动态加载运输公司列表
    function loadTransportCompanies() {
      fetch('/api/tires/transport-companies', {
        headers: {
          'Authorization': getAuthToken()
        }
      })
              .then(response => {
                if (!response.ok) {
                  throw new Error('网络响应不正常');
                }
                return response.json();
              })
              .then(companies => {
                const companySelect = document.getElementById('searchCompany');

                // 清空现有选项（除了"全部"选项）
                while (companySelect.options.length > 1) {
                  companySelect.remove(1);
                }

                // 添加新的运输公司选项
                companies.forEach(company => {
                  const option = document.createElement('option');
                  option.value = company;
                  option.textContent = company;
                  companySelect.appendChild(option);
                });

                console.log('加载运输公司列表成功，数量:', companies.length);
              })
              .catch(error => {
                console.error('加载运输公司列表失败:', error);
                if (error.message.includes('未登录') || error.message.includes('登录已过期')) {
                  localStorage.removeItem('token');
                  localStorage.removeItem('userInfo');
                  window.location.href = '/login';
                }
              });
    }


    // 为轮胎号搜索框添加自动补全功能
    $("#searchTireNumber").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "/api/tires/autocomplete/tire-numbers",
          dataType: "json",
          headers: {
            'Authorization': getAuthToken()
          },
          data: {
            term: request.term
          },
          beforeSend: function() {
            $("#searchTireNumber").addClass("ui-autocomplete-loading");
          },
          success: function(data) {
            response(data);
          },
          error: function(xhr, status, error) {
            if (xhr.status === 401) {
              localStorage.removeItem('token');
              localStorage.removeItem('userInfo');
              window.location.href = '/login';
            } else {
              response([]);
            }
          },
          complete: function() {
            $("#searchTireNumber").removeClass("ui-autocomplete-loading");
          }
        });
      },
      minLength: 1,
      delay: 300,
      select: function(event, ui) {
        $("#searchTireNumber").val(ui.item.value);
        return false;
      },
      focus: function(event, ui) {
        event.preventDefault();
      }
    });

    // 为车牌号搜索框添加自动补全功能
    $("#searchPlateNumber").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "/api/tires/autocomplete/plate-numbers",
          dataType: "json",
          headers: {
            'Authorization': getAuthToken()
          },
          data: {
            term: request.term
          },
          beforeSend: function() {
            $("#searchPlateNumber").addClass("ui-autocomplete-loading");
          },
          success: function(data) {
            response(data);
          },
          error: function(xhr, status, error) {
            if (xhr.status === 401) {
              localStorage.removeItem('token');
              localStorage.removeItem('userInfo');
              window.location.href = '/login';
            } else {
              response([]);
            }
          },
          complete: function() {
            $("#searchPlateNumber").removeClass("ui-autocomplete-loading");
          }
        });
      },
      minLength: 1,
      delay: 300,
      select: function(event, ui) {
        $("#searchPlateNumber").val(ui.item.value);
        return false;
      },
      focus: function(event, ui) {
        event.preventDefault();
      }
    });

    // 输入框获得焦点时自动选择所有文本
    $("#searchTireNumber, #searchPlateNumber").focus(function() {
      $(this).select();
    });

    // 表单提交事件
    $("#searchForm").submit(function(e) {
      e.preventDefault();
      tiresCurrentPage = 1;
      loadTires();
    });

    // 修改重置按钮事件
    $("#resetBtn").click(function() {
      const userInfo = getUserInfo();
      const userRole = userInfo ? userInfo.role : '';
      const userTransportCompany = userInfo ? userInfo.transportCompany : '';
      const userVehiclePlateNumber = userInfo ? userInfo.vehiclePlateNumber : '';

      // 重置表单
      $("#searchForm")[0].reset();

      // 根据用户角色重新设置固定值
      if (userRole === 'DRIVER' || userRole === 'COMPANY') {
        // 重新设置司机或公司角色的运输公司选项
        setupSearchFormForUserRole(userRole, userTransportCompany, userVehiclePlateNumber);
      }

      tiresCurrentPage = 1;
      loadTires();
    });
    // 添加键盘导航支持
    document.addEventListener('keydown', function(event) {
      if (event.key === 'ArrowLeft' && tiresCurrentPage > 1) {
        changeTiresPage(tiresCurrentPage - 1);
      } else if (event.key === 'ArrowRight' && tiresCurrentPage < tiresTotalPages) {
        changeTiresPage(tiresCurrentPage + 1);
      }
    });

    function loadTires() {
      const loadingOverlay = document.getElementById('loadingOverlay');
      loadingOverlay.style.display = 'flex';

      // 获取搜索条件
      const searchParams = {
        tireNumber: $("#searchTireNumber").val(),
        plateNumber: $("#searchPlateNumber").val(),
        company: $("#searchCompany").val(),
        status: $("#searchStatus").val()
      };

      // 构建查询参数
      const params = new URLSearchParams();
      if (searchParams.tireNumber) params.append('tireNumber', searchParams.tireNumber);
      if (searchParams.plateNumber) params.append('plateNumber', searchParams.plateNumber);
      if (searchParams.company) params.append('company', searchParams.company);
      if (searchParams.status) {
        // 将状态值转换为后端期望的格式
        const statusValue = searchParams.status === 'active' ? 'active' :
                searchParams.status === 'scrapped' ? 'scrapped' : '';
        if (statusValue) params.append('status', statusValue);
      }

      console.log('搜索参数:', Object.fromEntries(params));

      // 发送AJAX请求
      fetch(`/api/tires/search?${params}`, {
        headers: {
          'Authorization': getAuthToken(),
          'Content-Type': 'application/json'
        }
      })
              .then(response => {
                if (!response.ok) {
                  // 如果是权限错误，跳转到登录页
                  if (response.status === 401 || response.status === 403) {
                    throw new Error('未登录或权限不足');
                  }
                  return response.text().then(text => {
                    throw new Error(text || '网络响应不正常');
                  });
                }
                return response.json();
              })
              .then(data => {
                console.log('接收到的数据:', data);

                // 检查是否有错误信息
                if (data.error) {
                  throw new Error(data.error);
                }

                allTiresData = data.tires || [];
                tiresTotalRecords = allTiresData.length;
                tiresTotalPages = Math.ceil(tiresTotalRecords / tiresPageSize);

                updateTiresTable(getCurrentTiresPageData());
                updateTiresPagination();

                // 更新统计信息
                if (data.statistics) {
                  updateStatistics(data.statistics);
                } else {
                  // 如果没有统计信息，手动计算
                  updateStatistics({
                    totalTires: allTiresData.length,
                    activeTires: allTiresData.filter(t => !t.scrapDate).length,
                    scrappedTires: allTiresData.filter(t => t.scrapDate).length,
                    repairedTires: allTiresData.filter(t => t.repairRecords && t.repairRecords.trim() !== '').length
                  });
                }
              })
              .catch(error => {
                console.error('加载轮胎数据失败:', error);

                // 检查错误类型
                if (error.message.includes('未登录') || error.message.includes('权限不足') || error.message.includes('401') || error.message.includes('403')) {
                  localStorage.removeItem('token');
                  localStorage.removeItem('userInfo');
                  window.location.href = '/login';
                } else {
                  // 显示更友好的错误信息
                  const errorMsg = error.message.includes('Network') ?
                          '网络连接失败，请检查网络连接' :
                          '加载数据失败: ' + error.message;

                  alert(errorMsg);
                }

                allTiresData = [];
                tiresTotalRecords = 0;
                tiresTotalPages = 1;
                updateTiresTable([]);
                updateTiresPagination();
                updateStatistics({
                  totalTires: 0,
                  activeTires: 0,
                  scrappedTires: 0,
                  repairedTires: 0
                });
              })
              .finally(() => {
                loadingOverlay.style.display = 'none';
              });
    }

    // 获取当前页的轮胎数据
    function getCurrentTiresPageData() {
      const startIndex = (tiresCurrentPage - 1) * tiresPageSize;
      const endIndex = Math.min(startIndex + tiresPageSize, allTiresData.length);
      return allTiresData.slice(startIndex, endIndex);
    }

    function updateTiresTable(tires) {
      const tbody = document.getElementById('tiresTableBody');
      tbody.innerHTML = '';

      if (!tires || tires.length === 0) {
        tbody.innerHTML = `
          <tr>
            <td colspan="11" class="text-center py-4">
              <div class="text-muted">
                <i class="fas fa-inbox fa-2x mb-3"></i>
                <p>暂无轮胎数据</p>
              </div>
            </td>
          </tr>
        `;
        return;
      }

      tires.forEach((tire, index) => {
        const row = document.createElement('tr');
        if (tire.scrapDate) {
          row.classList.add('table-secondary');
        }

        // 构建车牌号显示
        let plateNumberDisplay = '未安装';
        if (tire.vehiclePlateNumber || tire.trailerPlateNumber) {
          plateNumberDisplay = [tire.vehiclePlateNumber, tire.trailerPlateNumber]
                  .filter(Boolean)
                  .join(' / ');
        }

        // 构建状态徽章
        let statusBadges = '';
        if (tire.scrapDate === null) {
          statusBadges += '<span class="badge bg-success status-badge">使用中</span>';
        } else {
          statusBadges += '<span class="badge bg-secondary status-badge">已报废</span>';
        }
        if (tire.repairRecords && tire.repairRecords.trim() !== '') {
          statusBadges += '<span class="badge bg-warning status-badge">有修补</span>';
        }

        row.innerHTML = `
          <td><strong>${tire.tireNumber}</strong></td>
          <td>${plateNumberDisplay}</td>
          <td>
            ${tire.axleNumber ? `<span class="badge axle-badge">${tire.axleNumber}轴</span>` : ''}
            ${tire.tirePosition || '--'}
          </td>
          <td>${tire.transportCompany || '--'}</td>
          <td>${tire.tireBrand || '--'}</td>
          <td>${tire.tireModel || '--'}</td>
          <td>${tire.installDate || '--'}</td>
          <td>${tire.installMileage || '--'}</td>
          <td>
            ${tire.scrapMileage ? tire.scrapMileage : '<span class="text-muted">使用中</span>'}
          </td>
          <td>${statusBadges}</td>
          <td class="action-buttons">
            <a href="/api/tires/${tire.id}" class="btn btn-sm btn-info" title="查看详情">详情</a>
            <a href="/api/tires/usage?tireNumber=${tire.tireNumber}" class="btn btn-sm btn-primary" title="查询使用记录">记录</a>
            <a href="/api/tires/${tire.id}/edit" class="btn btn-sm btn-success" title="修改轮胎信息">修改</a>
            ${tire.scrapDate === null ? `<a href="/api/tires/${tire.id}/repair" class="btn btn-sm btn-warning" title="添加修补记录">修补</a>` : ''}
          </td>
        `;
        tbody.appendChild(row);
      });
    }

    // 更新轮胎列表分页
    function updateTiresPagination() {
      const paginationContainer = document.getElementById('tiresPagination');
      const pageInfoContainer = document.getElementById('tiresPageInfo');

      // 更新页面信息
      const startIndex = (tiresCurrentPage - 1) * tiresPageSize + 1;
      const endIndex = Math.min(tiresCurrentPage * tiresPageSize, tiresTotalRecords);
      pageInfoContainer.textContent = `显示 ${startIndex}-${endIndex} 条，共 ${tiresTotalRecords.toLocaleString()} 条`;

      if (tiresTotalRecords === 0) {
        paginationContainer.innerHTML = '';
        return;
      }

      let paginationHTML = '';

      // 上一页按钮
      if (tiresCurrentPage > 1) {
        paginationHTML += `
        <li class="page-item">
          <a class="page-link" href="#" onclick="changeTiresPage(${tiresCurrentPage - 1}); return false;">
            <i class="fas fa-chevron-left"></i> 上一页
          </a>
        </li>
      `;
      } else {
        paginationHTML += `
        <li class="page-item disabled">
          <span class="page-link">
            <i class="fas fa-chevron-left"></i> 上一页
          </span>
        </li>
      `;
      }

      // 计算要显示的页码范围
      const maxVisiblePages = 5;
      let startPage = Math.max(1, tiresCurrentPage - Math.floor(maxVisiblePages / 2));
      let endPage = Math.min(tiresTotalPages, startPage + maxVisiblePages - 1);

      if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
      }

      // 第一页和省略号
      if (startPage > 1) {
        paginationHTML += `
        <li class="page-item">
          <a class="page-link" href="#" onclick="changeTiresPage(1); return false;">1</a>
        </li>
      `;
        if (startPage > 2) {
          paginationHTML += `
          <li class="page-item disabled">
            <span class="page-link">...</span>
          </li>
        `;
        }
      }

      // 页码按钮
      for (let i = startPage; i <= endPage; i++) {
        if (i === tiresCurrentPage) {
          paginationHTML += `
          <li class="page-item active">
            <a class="page-link" href="#">${i}</a>
          </li>
        `;
        } else {
          paginationHTML += `
          <li class="page-item">
            <a class="page-link" href="#" onclick="changeTiresPage(${i}); return false;">${i}</a>
          </li>
        `;
        }
      }

      // 最后一页和省略号
      if (endPage < tiresTotalPages) {
        if (endPage < tiresTotalPages - 1) {
          paginationHTML += `
          <li class="page-item disabled">
            <span class="page-link">...</span>
          </li>
        `;
        }
        paginationHTML += `
        <li class="page-item">
          <a class="page-link" href="#" onclick="changeTiresPage(${tiresTotalPages}); return false;">${tiresTotalPages}</a>
        </li>
      `;
      }

      // 下一页按钮
      if (tiresCurrentPage < tiresTotalPages) {
        paginationHTML += `
        <li class="page-item">
          <a class="page-link" href="#" onclick="changeTiresPage(${tiresCurrentPage + 1}); return false;">
            下一页 <i class="fas fa-chevron-right"></i>
          </a>
        </li>
      `;
      } else {
        paginationHTML += `
        <li class="page-item disabled">
          <span class="page-link">
            下一页 <i class="fas fa-chevron-right"></i>
          </span>
        </li>
      `;
      }

      paginationContainer.innerHTML = paginationHTML;
    }

    // 切换轮胎列表页码
    function changeTiresPage(page) {
      if (page < 1 || page > tiresTotalPages || page === tiresCurrentPage) {
        return;
      }

      tiresCurrentPage = page;
      updateTiresTable(getCurrentTiresPageData());
      updateTiresPagination();

      const tableElement = document.querySelector('.table');
      if (tableElement) {
        tableElement.scrollIntoView({behavior: 'smooth', block: 'start'});
      }
    }

    function updateStatistics(statistics) {
      document.getElementById('totalTiresCount').textContent = statistics.totalTires || 0;
      document.getElementById('activeTiresCount').textContent = statistics.activeTires || 0;
      document.getElementById('scrappedTiresCount').textContent = statistics.scrappedTires || 0;
      document.getElementById('repairedTiresCount').textContent = statistics.repairedTires || 0;
    }

    // 将 changeTiresPage 函数暴露给全局作用域，以便分页按钮调用
    window.changeTiresPage = changeTiresPage;
  }
</script>
</body>
</html>